package com.ellecity06.cwhiskymall.ui.search

import androidx.lifecycle.viewModelScope
import com.ellecity06.common.base.BaseMviViewModel
import com.ellecity06.common.delegate.mmkv
import com.ellecity06.common.ktx.postEvent
import com.ellecity06.common.utils.gson
import com.ellecity06.cwhiskymall.bean.TagItem
import com.ellecity06.cwhiskymall.bean.request.GoodRequest
import com.ellecity06.cwhiskymall.bean.request.SearchDiscoveryRequest
import com.ellecity06.cwhiskymall.http.request
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.launch

/**
 * @author ellecity06
 * @time 2024/11/1 17:13
 * @des
 */
class SearchViewModel : BaseMviViewModel<SearchState, SearchIntent>() {

    private var keyword: String? = null
    override suspend fun collectIntent(it: SearchIntent) {


        when (it) {
            SearchIntent.DeleteHistory -> {
                deleteHistory()
                mState.postEvent(SearchState.HistoryList(getHistory()))

            }

            is SearchIntent.AddHistory -> {
                putHistoryKey(it.keyword)
                mState.postEvent(SearchState.HistoryList(getHistory()))
            }

            is SearchIntent.Search -> {
                pagerHelper.pageIndex = 1
                this.keyword = it.keyword
                // 历史搜索点击的时候需要显示结果页
                mState.postEvent(SearchState.ShowResultFragment(it.keyword))
                search()
            }

            is SearchIntent.Refresh -> {
                pagerHelper.pageIndex = 1
                search()
            }

            is SearchIntent.LoadMore -> {
                search()
            }

            SearchIntent.FetchHistory -> {
                mState.postEvent(SearchState.HistoryList(getHistory()))
            }

            SearchIntent.SearchDiscovery -> {
                pagerHelper.pageIndex=1
                searchDiscovery()
            }
            SearchIntent.LoadMoreDiscovery -> {
                searchDiscovery()
            }

            else -> {}
        }
    }

    private fun searchDiscovery() {
        val pageRequest = SearchDiscoveryRequest()
        pageRequest.pageNum = pagerHelper.pageIndex
        pageRequest.pageSize = 50
        request(api = { searchDiscovery(pageRequest) }, success = {
            if (it != null) {
                if (pagerHelper.pageIndex==1){
                    // 刷新
                    if (!it.hotSearchTerms.isNullOrEmpty()) {
                        mState.postEvent(SearchState.SearchDiscoverList(it.hotSearchTerms))
                    }
                    if (it.hotSearchSpuVos != null) {
                        // 热搜顶部
                        val hotList = it.hotSearchSpuVos
                        val hasMore = hotList.size >= pageRequest.pageSize
                        if (hotList.size >= 4) {
                            mState.postEvent(SearchState.SearchHotTopList(hotList.subList(0, 3)))

                            mState.postEvent(SearchState.SearchHotList(hotList.subList(3, hotList.size),hasMore))
                        } else {
                            mState.postEvent(SearchState.SearchHotList(hotList,hasMore))
                        }

                    }
                }else{
                    // 热搜顶部
                    val hotList = it.hotSearchSpuVos!!
                    val hasMore = hotList.size >= pageRequest.pageSize
                    mState.postEvent(SearchState.SearchHotMoreList(hotList,hasMore))
                }
                pagerHelper.pageIndex++
            }
        })
    }

    private fun search() {
        val request = GoodRequest(goodsName = keyword)
        request.pageNum = pagerHelper.pageIndex
        request.pageSize = 10
        request(api = { goodList(request) }, success = {
            if (it != null) {
                if (!it.records.isNullOrEmpty()) {
                    val hasMore = it.records.size >= request.pageSize
                    if (pagerHelper.pageIndex == 1) {
                        mState.postEvent(SearchState.RefreshSuccess(it.records, hasMore))
                    } else {
                        mState.postEvent(SearchState.LoadMoreSuccess(it.records, hasMore))
                    }
                    pagerHelper.pageIndex++
                } else {
                    if (pagerHelper.pageIndex == 1) {
                        mState.postEvent(SearchState.RefreshSuccess(mutableListOf(), false))
                    } else {
                        mState.postEvent(SearchState.NoMore)
                    }
                }
            }

        }, error = {
            viewModelScope.launch { mState.postEvent(SearchState.LoadError) }
        })
    }

    private fun deleteHistory() {
        mmkv.encode("search_history", gson.toJson(mutableListOf<TagItem>()))
    }

    private fun putHistoryKey(keyword: String) {
        val list: MutableList<TagItem> = gson.fromJson(
            mmkv.decodeString("search_history"),
            object : TypeToken<MutableList<TagItem>>() {}.type
        ) ?: mutableListOf()
        list.forEach {
            if (it.name == keyword) return
        }
        if (list.size >= 30) {
            val subList = list.subList(0, 30)
            subList.add(0, TagItem(keyword))
            mmkv.encode("search_history", gson.toJson(subList))
        } else {
            list.add(0, TagItem(keyword))
            mmkv.encode("search_history", gson.toJson(list))
        }
    }

    private fun getHistory(): MutableList<TagItem> {
        return gson.fromJson(
            mmkv.decodeString("search_history"),
            object : TypeToken<MutableList<TagItem>>() {}.type
        ) ?: mutableListOf()
    }
}